#include "stdafx.h"

#include "pthread.h"
#include <iostream>
#include "windows.h"

using namespace std;

//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int g_tmp = 0;
bool g_bExit = true;

static void add1(int& tmp)
{
	cout << pthread_self().p <<" : "<< tmp++ << endl;
}

void* thread(void *arg)
{	
	Sleep(20);
	while (!g_bExit)
	{
		pthread_mutex_lock(&mutex);
		for (int i = 0; i < 5; i++)
		{
			add1(g_tmp);
			Sleep(1000);
		}
		cout << endl;
		pthread_mutex_unlock(&mutex);
		Sleep(20);
	}
	
	return NULL;
}

void testMutex()
{
	pthread_t id;
	cout << "main thread id is " << pthread_self().p << endl;

	const int iMax_Threads = 3;
	pthread_t* ids = new pthread_t[iMax_Threads];
	g_bExit = false;
	pthread_mutex_init(&mutex,NULL);
	for (int i = 0 ;i < iMax_Threads;i++)
	{
		if (!pthread_create(&ids[i], NULL, thread, NULL))
		{
			cout << "Create thread success : "<<ids[i].p << endl;
		}
		else
		{
			cout << "Create thread failed!" << endl;
		}
	}

	for (int i = 0; i < iMax_Threads; i++)
	{
		pthread_join(ids[i], NULL);
	}
	
	pthread_mutex_destroy(&mutex);
}
